package com.shqcjd.yunweiyanoperator.ui.fragment;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.afollestad.materialdialogs.MaterialDialog;
import com.google.gson.Gson;
import com.gyf.immersionbar.ImmersionBar;
import com.shqcjd.yunweiyanoperator.R;
import com.shqcjd.yunweiyanoperator.api.ApiService;
import com.shqcjd.yunweiyanoperator.helper.rxjavahelper.RxObserver;
import com.shqcjd.yunweiyanoperator.helper.rxjavahelper.RxSchedulersHelper;
import com.shqcjd.yunweiyanoperator.model.ResponseData;
import com.shqcjd.yunweiyanoperator.model.eventbus.ReloginEvent;
import com.shqcjd.yunweiyanoperator.model.pojo.GoRegister;
import com.shqcjd.yunweiyanoperator.model.pojo.LoginBean;
import com.shqcjd.yunweiyanoperator.ui.activity.AdministerMainActivity;
import com.shqcjd.yunweiyanoperator.ui.activity.CollectionActivity;
import com.shqcjd.yunweiyanoperator.ui.activity.FollowListActivity;
import com.shqcjd.yunweiyanoperator.ui.activity.GenerateQRcodeActivity;
import com.shqcjd.yunweiyanoperator.ui.activity.QRcodeActivity;
import com.shqcjd.yunweiyanoperator.ui.activity.RepairRecordActivity;
import com.shqcjd.yunweiyanoperator.ui.activity.SetActivity;
import com.shqcjd.yunweiyanoperator.ui.activity.ShareActivity;
import com.shqcjd.yunweiyanoperator.ui.activity.mine.LearningVideoActivity;
import com.shqcjd.yunweiyanoperator.ui.activity.mine.MyVideoActivity;
import com.shqcjd.yunweiyanoperator.ui.activity.mine.RecommendListActivity;
import com.shqcjd.yunweiyanoperator.ui.activity.UploadFileActivity;
import com.shqcjd.yunweiyanoperator.ui.activity.staff.ContactsActivity;
import com.shqcjd.yunweiyanoperator.ui.base.BaseFragment;
import com.shqcjd.yunweiyanoperator.ui.base.BasePresenter;
import com.shqcjd.yunweiyanoperator.util.PrefUtils;
import com.shqcjd.yunweiyanoperator.util.ToastUtils;
import com.shqcjd.yunweiyanoperator.widget.AddTipDialog;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

import static android.app.Activity.RESULT_OK;

/**
 * 我的
 * Created by sy on 2019/3/14.
 */

public class MineFragment extends BaseFragment {


    @BindView(R.id.rl_frag_mine_collection)
    RelativeLayout rlFragMineCollection;
    @BindView(R.id.rl_frag_mine_set)
    RelativeLayout rlFragMineSet;
    @BindView(R.id.tv_frag_mine_scan)
    TextView tvFragMineScan;
    @BindView(R.id.iv_frag_mine_qcode)
    ImageView ivFragMineQcode;
    @BindView(R.id.rl_frag_mine_record)
    RelativeLayout rlFragMineRecord;
    @BindView(R.id.rl_frag_mine_share)
    RelativeLayout rlFragMineShare;
    @BindView(R.id.rl_contacts)
    RelativeLayout rl_contacts;

    @BindView(R.id.tv_frag_mine_name)
    TextView tvFragMineName;
    @BindView(R.id.tv_frag_mine_phone)
    TextView tvFragMinePhone;
    @BindView(R.id.rl_administer)
    RelativeLayout rl_administer;
    @BindView(R.id.tv_info)
    TextView tv_info;
    @BindView(R.id.rl_follow)
    RelativeLayout rl_follow;
    @BindView(R.id.rl_learning)
    RelativeLayout rl_learning;
    @BindView(R.id.rl_recommend)
    RelativeLayout rl_recommend;
    @BindView(R.id.flowlayout)
    TagFlowLayout flowlayout;
    @BindView(R.id.rl_my_video)
    RelativeLayout rl_my_video;

    private Context mContext;
    public static final int REQUEST_CODE = 100;
    private AddTipDialog addTipDialog;
    private int userType;
    private String departmentName;
    ArrayList<String> mTypeVals = new ArrayList<>();
    private LoginBean loginBean;

    public static MineFragment newInstance() {
        return new MineFragment();
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.fragment_mine;
    }

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    @Override
    public void init() {
        super.init();
        mContext = getActivity();
    }

    @Override
    public void initView(View rootView) {
        String loginJson = PrefUtils.getString(mContext, PrefUtils.LOGIN_BEAN, null);
        loginBean = new Gson().fromJson(loginJson, LoginBean.class);
        userType = PrefUtils.getInt(mContext, PrefUtils.USER_TYPE, -1);
        String name = PrefUtils.getString(mContext, PrefUtils.USER_NAME, "");
        departmentName = PrefUtils.getString(mContext, PrefUtils.DEPARTMENTNAME, null);
        tvFragMineName.setText(name + (departmentName == null ? "" : " ("+departmentName+")"));
        tvFragMinePhone.setText(PrefUtils.getString(mContext, PrefUtils.PHONE_NUMBER, "") + (!PrefUtils.getString(mContext, PrefUtils.BUSINESSNAME, "").equals("") ? "(" + PrefUtils.getString(mContext, PrefUtils.BUSINESSNAME, "") + ")" : ""));
        if (userType == 3) {//游客
            tvFragMinePhone.setVisibility(View.GONE);
        }else {
            tvFragMinePhone.setVisibility(View.VISIBLE);
            setTagView();
        }
        if (userType == 1) {
            rl_administer.setVisibility(View.VISIBLE);
        } else {
            rl_administer.setVisibility(View.GONE);
        }



    }

    /**
     * 设置专业tag
     */
    private void setTagView(){
        if (loginBean!=null&&loginBean.major != null && loginBean.major.size() > 0) {
            mTypeVals.clear();
            for (LoginBean.MajorBean majorBean : loginBean.major) {
                if (majorBean!=null) {
                    mTypeVals.add(majorBean.name);
                }
            }
        }

        TagAdapter tagAdapter = new TagAdapter<String>(mTypeVals.toArray(new String[mTypeVals.size()])) {
            @Override
            public View getView(FlowLayout parent, int position, String s) {
                TextView tv = (TextView) LayoutInflater.from(mContext).inflate(R.layout.tv_my_major_tag,
                        flowlayout, false);
                tv.setText(s);
                return tv;
            }

        };
        flowlayout.setAdapter(tagAdapter);
    }


    @OnClick({R.id.rl_frag_mine_collection, R.id.rl_frag_mine_set, R.id.tv_frag_mine_scan, R.id.iv_frag_mine_qcode,
            R.id.rl_frag_mine_record, R.id.rl_frag_mine_share, R.id.rl_contacts, R.id.rl_administer,R.id.rl_follow,R.id.rl_learning,R.id.rl_recommend,R.id.rl_my_video})
    public void onViewClicked(View view) {
        if (userType == 3) {//游客
            if (view.getId() == R.id.rl_frag_mine_set) {
                Intent itSet = new Intent(mContext, SetActivity.class);
                startActivity(itSet);
            } else {
                showLoginDialog();
            }
            return;
        }

        switch (view.getId()) {
            case R.id.rl_frag_mine_collection://收藏列表
                Intent it = new Intent(mContext, CollectionActivity.class);
                startActivity(it);
                break;
            case R.id.rl_frag_mine_set://设置
                Intent itSet = new Intent(mContext, SetActivity.class);
                startActivity(itSet);
                break;
            case R.id.tv_frag_mine_scan:
                RxPermissions permissions = new RxPermissions(getActivity());
                permissions.setLogging(true);
                permissions.request(Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE)
                        .subscribe(new Consumer<Boolean>() {
                            @Override
                            public void accept(Boolean aBoolean) throws Exception {
                                if (aBoolean) {
                                    startActivityForResult(new Intent(mContext, QRcodeActivity.class), REQUEST_CODE);
                                } else {
                                    ToastUtils.show(getActivity(), "扫描二维码需要打开相机和闪光灯的权限", Toast.LENGTH_SHORT);
                                }
                            }
                        });
                break;
            case R.id.iv_frag_mine_qcode:
                Intent itQcode = new Intent(getContext(), GenerateQRcodeActivity.class);
                String friendAppCode = PrefUtils.getString(mContext, PrefUtils.APPCODE, "");
                String friendId = PrefUtils.getInt(mContext, PrefUtils.USER_ID, -1) + "";
                String friendName = PrefUtils.getString(mContext, PrefUtils.USER_NAME, "") + "";
                Map<String, String> map = new HashMap<>();
                map.put("friendAppCode", friendAppCode);
                map.put("friendId", friendId);
                map.put("friendName", friendName);
                String json = new JSONObject(map).toString();
                itQcode.putExtra("QRcode", json);
                startActivity(itQcode);
                break;
            case R.id.rl_frag_mine_record://维修记录
                Intent itRecord = new Intent(getContext(), RepairRecordActivity.class);
                startActivity(itRecord);
//                Intent i = new Intent(getContext(), UploadFileActivity.class);
//                startActivity(i);
                break;
            case R.id.rl_frag_mine_share://分享
                Intent itShare = new Intent(getContext(), ShareActivity.class);
                startActivity(itShare);
                break;
            case R.id.rl_contacts://好友列表
                Intent itContacts = new Intent(getContext(), ContactsActivity.class);
                itContacts.putExtra("type", 0);
                startActivity(itContacts);
                break;
            case R.id.rl_administer://企业管理
                startActivity(new Intent(getContext(), AdministerMainActivity.class));
                break;
            case R.id.rl_follow://关注列表
                startActivity(new Intent(getContext(), FollowListActivity.class));
                break;
            case R.id.rl_learning://学习
                startActivity(new Intent(getContext(), LearningVideoActivity.class));
                break;
            case R.id.rl_recommend://推荐人群
                startActivity(new Intent(getContext(), RecommendListActivity.class));
                break;
            case R.id.rl_my_video://我的视频
                startActivity(new Intent(getContext(), MyVideoActivity.class));
                break;

        }
    }

    private void showLoginDialog() {
        final MaterialDialog dialog = new MaterialDialog.Builder(getContext())
                .customView(R.layout.custome_login_layout, false)
                .show();
        dialog.getWindow().setBackgroundDrawableResource(R.color.transparent);
        View customeView = dialog.getCustomView();
        TextView tv_confirm = customeView.findViewById(R.id.tv_confirm);
        TextView tv_cancel = customeView.findViewById(R.id.tv_cancel);
        tv_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EventBus.getDefault().post(new GoRegister());
                dialog.dismiss();
            }
        });

        tv_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
    }



    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (REQUEST_CODE == requestCode && RESULT_OK == resultCode) {
            String value = data.getStringExtra("qr_code_key");
            if (value.contains("friendId")) {
                addTipDialog = new AddTipDialog(mContext);
                addTipDialog.setOnClickDialogListener(new AddTipDialog.setOnClickDialogListener() {
                    @Override
                    public void onClickAdd() {
//                            String friendAppCode = value.substring(0, value.indexOf("~"));
//                            String str = value.substring(0, value.indexOf("~"));
//                            String friendId = value.substring(str.length()+1, value.length());
                        addContactsHttp(value);
                        addTipDialog.dismiss();
                    }
                });
                addTipDialog.show();
            } else {
                ToastUtils.showShort(mContext, "请扫描正确的二维码");
            }
        }
    }

    /**
     * 添加好友
     */
    private void addContactsHttp(String json) {
        ApiService.addContacts(json)
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                    }

                    @Override
                    public void _onNext(ResponseData responseData) {
                        if (responseData.retCode == 10000) {
                            ToastUtils.showShort(mContext, "添加好友的请求已经发送给对方");
                        } else {
                            ToastUtils.showShort(mContext, responseData.retMsg);
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        Log.e("tou", errorMessage);
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                    }
                });
    }

    @Override
    public void initImmersionBar() {
        super.initImmersionBar();
        ImmersionBar.with(this)
                .statusBarDarkFont(true)
                .navigationBarColor(R.color.colorPrimary)
                .statusBarDarkFont(true, 0.2f)
                .navigationBarDarkIcon(true)
                .init();
    }


}